package com.miniserver.wx.service;

import java.net.URLDecoder;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.miniserver.tql.database.DatabaseEngine;
import com.miniserver.tql.database.EngineContext;
import com.miniserver.tql.database.model.TNode;
import com.miniserver.wx.utils.WxUtil;

public class WxBaseSev {
	/**
	 * 根据参数获取accessToken
	 * @param engine
	 * @param context
	 * @param tNode
	 * @throws Exception
	 */
	public void generateAccessToken(DatabaseEngine engine, EngineContext context, TNode tNode) throws Exception {
		TNode throwNode = tNode.getChildren()[0];
		TNode throwUnknowNode = tNode.getChildren()[1];
		String appId = context.get("?appid");
		String appSecret = context.get("?appsecret");
		
		JSONObject result = new JSONObject();
		if(StringUtils.isBlank(appId) || StringUtils.isBlank(appSecret)) {
			engine.invoke(context, throwNode);
		} else {
			String accessToken = WxUtil.generateAccessToken(appId, appSecret);
			if(StringUtils.isNotBlank(accessToken)) {
				result.put("success", true);
				result.put("accesstoken", accessToken);
			} else {
				engine.invoke(context, throwUnknowNode);
			}
		}
		
		context.put("@return", result.toString());
	}
	
	/**
	 * 根据参数获取accessToken
	 * @param engine
	 * @param context
	 * @param tNode
	 * @throws Exception
	 */
	public void generateJsapiTicket(DatabaseEngine engine, EngineContext context, TNode tNode) throws Exception {
		TNode throwNode = tNode.getChildren()[0];
		TNode throwUnknowNode = tNode.getChildren()[1];
		String appId = context.get("?appid");
		String appSecret = context.get("?appsecret");
		String url = URLDecoder.decode(context.get("?url"), "UTF-8");
		
		JSONObject result = new JSONObject();
		if(StringUtils.isBlank(appId) || StringUtils.isBlank(appSecret) || StringUtils.isBlank(url)) {
			engine.invoke(context, throwNode);
		} else {
			JSONObject ticketObj = WxUtil.generateJsapiTicket(appId, appSecret, url);
			if(ticketObj.optBoolean("success", false)) {
				result = ticketObj;
			} else {
				engine.invoke(context, throwUnknowNode);
			}
		}
		
		context.put("@return", result.toString());
	}
}